********************************************************************************
* Replication file for Cui (2020 JEEM)
* "Climate change and adaptation in agriculture: Evidence from US cropping patterns"
*
* Step 1.2: Merge across datasets to form county-year panel
********************************************************************************

* set path
	
	global family "..."
	global data  ".../dta"

* load data: county-level crop data

	use $data/pl_acre_yield_4crops, clear
	
	gen fips = stateansi*1000 + countyansi

* merge with other crops

	* spring wheat
	merge 1:1 fips year using $data/pl_acre_sprwht
	drop _merge
	* barley
	merge 1:1 fips year using $data/pl_acre_barley
	drop _merge		
	* sorghum
	merge 1:1 fips year using $data/pl_acre_sorghum
	drop _merge		
	
* restrict to post-1980

	keep if year>1980
	
* merge with weather data (GS: Apr - Sep)

	merge 1:1 fips year using $data/prism_aw_county_apr_sep
	drop if year==2016
	drop if _merge==1
	drop _merge

* merge with irrigation data
	merge 1:1 fips year using $data/census_irrigation
	drop if _merge==2
	drop _merge
	
* irrigation intensity measure (time-invariant)
	egen irr_ratio = mean(irrigation_ratio), by(fips)
	
* merge with irrigated harvest acres 
	merge 1:1 fips year using $data/irracres_cs
	drop _merge		
	
* label unbalanced
	gen count = 1
	foreach x in corn soy wheat cotton sprwht barley sorghum {
		egen pl_yrs_`x' = total(count*(pl_acre_`x'!=.)), by(fips)
		}

* replace yield = 0 for missing yield but positive planted acres
	foreach x in corn soy wheat cotton {
		replace yield_`x' = 0 if yield_`x'==. & pl_acre_`x'!=.
		}
	
* recode state stateansi		
	drop state stateansi county countyansi
	run $family/do/trans_state
	
* merge with long & lat info
	merge m:1 fips using $data/fips_lon_lat_lower48states
	drop if _merge!=3
	drop _merge
	
* merge with population		
	merge 1:1 fips year using $data/county_population_1970_2016
	drop if _merge==2
	drop _merge
	
* merge with CRP info
	merge 1:1 fips year using $data/crp_area
	drop if _merge==2
	replace crp_area = 0 if crp_area==.
	drop _merge
	
* merge with crop insurance
	merge 1:1 fips year using $data/insured_acres	
	drop if _merge==2
	drop _merge
	
* merge with cash rent (deflated)
	merge 1:1 fips year using $data/cashrent_county
	drop if _merge==2
	drop _merge	

	merge m:1 stateansi year using $data/cashrent_state
	drop if _merge==2
	drop _merge	
	
	gen cashrent_dfl = .
	replace cashrent_dfl = cashrent_county_dfl if cashrent_county_dfl!=.
	replace cashrent_dfl = cashrent_state_dfl if cashrent_state_dfl!=.
	
* merge with price data
	merge m:1 stateansi year using $data/price_dfl_1969_14
	drop _merge	
	
	* save
	save $data/merged_clim_ag, replace	
